import mysql from "mysql2/promise";

const config = useRuntimeConfig().db;
// 数据库配置
export const dbConfig = {
  host: config.DB_HOST || "localhost",
  port: parseInt(config.DB_PORT || "3306"),
  user: config.DB_USER || "root",
  password: config.DB_PASSWORD || "",
  database: config.DB_NAME || "nuxt_blog",
  charset: "utf8mb4",
  timezone: "+08:00",
};


// 创建数据库连接池
export const pool = mysql.createPool({
  ...dbConfig,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
  // 连接池优化配置
  idleTimeout: 60000, // 空闲连接超时时间
  // 保持连接配置
  enableKeepAlive: true, // 启用保持连接
  keepAliveInitialDelay: 0, // 保持连接初始延迟
});

pool.on("enqueue", () => {
  console.log("⏳ 查询进入队列，等待可用连接...");
});

// 数据库连接测试
export async function testConnection() {
  try {
    const connection = await pool.getConnection();
    console.log("✅ 数据库连接成功");
    connection.release();
    return true;
  } catch (error) {
    console.error("❌ 数据库连接失败:", error);
    return false;
  }
}

// 定期检查连接池健康状态
export async function checkPoolHealth(): Promise<boolean> {
  try {
    const connection = await pool.getConnection();
    await connection.execute("SELECT 1 as health_check");
    connection.release();
    // console.log("✅ 连接池健康检查通过");
    return true;
  } catch (error) {
    console.error("❌ 连接池健康检查失败:", error);
    return false;
  }
}

// 重启连接池（在严重错误时使用）
export async function restartPool(): Promise<void> {
  console.log("🔄 重启数据库连接池...");
  await pool.end();

  // 重新创建连接池
  Object.assign(
    pool,
    mysql.createPool({
      ...dbConfig,
      waitForConnections: true,
      connectionLimit: 10,
      queueLimit: 0,
      idleTimeout: 60000,
      enableKeepAlive: true,
      keepAliveInitialDelay: 0,
    })
  );

  console.log("✅ 连接池重启完成");
}
